package cn.itsource.itsource.service.impl;

import cn.itsource.itsource.domain.Shop;
import cn.itsource.itsource.domain.Employee;
import cn.itsource.itsource.domain.LinYu;
import cn.itsource.itsource.domain.ShopDto;
import cn.itsource.itsource.mapper.EmployeeMapper;
import cn.itsource.itsource.mapper.ShopMapper;
import cn.itsource.itsource.query.ShopQuery;
import cn.itsource.itsource.service.IShopService;
import cn.itsource.itsource.util.AjaxResult;
import cn.itsource.itsource.util.PageList;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ShopServiceImpl implements IShopService {
    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public AjaxResult register(ShopDto shopDto) {

        //TODO 数据校验:无论前端是否进行了非空校验,后台业务都必须将前端的所有校验,再判断一次!!!
        //TODO 防止请求后台时,直接绕过前端,导致后台产生垃圾数据!!!
        //1. 非空校验(关于字符串的操作,统一使用 commons.lang3包---->StringUtils)
        if (StringUtils.isAnyBlank(shopDto.getShop().getName(), shopDto.getShop().getAddress(), shopDto.getShop().getTel(),
                shopDto.getEmployee().getUsername(), shopDto.getEmployee().getPhone())) {
            return AjaxResult.error("缺少必填参数");
        }

        //2. 数据不能重复的校验
        //2.1 店铺名称不能重复

        //2.2 管理员登录帐号不能重复



        //1 将属于t_employee的数据插入员工表
        shopDto.getEmployee().setState(Employee.STATE_ZHENGCHANG);
        employeeMapper.save(shopDto.getEmployee());

        //TODO 在添加数据到数据库,表中的默认字段需要在后台直接给值
        shopDto.getShop().setRegisterTime(new Date());
        shopDto.getShop().setState(Shop.STATE_DAISHENGHE);

        Long id = shopDto.getEmployee().getId();
        //System.out.println(id);
        shopDto.getShop().setAdminId(id);
        //2 将属于t_shop的数据插入店铺表
        shopMapper.save(shopDto.getShop());


        return AjaxResult.success("入驻成功");
    }

    @Override
    public AjaxResult pageList(ShopQuery query) {
        PageHelper.startPage(query.getCurrPage(),query.getPageSize());
        PageInfo<Shop> pageInfo = new PageInfo<>(shopMapper.findByQuery(query));

        PageList<LinYu> pageList=new PageList(pageInfo.getTotal(),pageInfo.getList());
        AjaxResult result = AjaxResult.success("操作成功");
        result.setData(pageList);

        return  result;
    }
}
